package com.zf.shuashua.ui.mine;

import android.graphics.Color;
import android.graphics.SurfaceTexture;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Surface;
import android.view.TextureView;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.aliyun.svideo.base.utils.Eyes;
import com.aliyun.svideo.common.utils.NotchScreenUtil;
import com.zf.shuashua.R;

import java.io.IOException;

public class VideoPreviewActivity extends FragmentActivity {

    public static final String KEY_PATH_VIDEO = "video_path";

    private String mVideoPath;

    private TextureView mTextureView;

    private MediaPlayer mMediaPlayer;
    private Surface mPlayerSurface;

    private float mRatio;

    /**
     * 页面是否处于后台/为了解决部分手机锁屏会重置SurfaceTexture，在后台恢复播放的问题
     */
    private boolean isBackground = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 检测是否是全面屏手机, 如果不是, 设置FullScreen
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (!NotchScreenUtil.checkNotchScreen(this)) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);

        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.alivc_editor_activity_video_preview);

        mVideoPath = getIntent().getStringExtra(KEY_PATH_VIDEO);
        mTextureView = (TextureView) findViewById(R.id.texture);
        isBackground = false;
        mTextureView.setSurfaceTextureListener(mlistener);

        findViewById(R.id.iv_left).setOnClickListener(v -> finish());

    }

    private final TextureView.SurfaceTextureListener mlistener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            initVideoPlayer();
            mPlayerSurface = new Surface(surface);
            try {
                mMediaPlayer.setDataSource(mVideoPath);
                mMediaPlayer.setSurface(mPlayerSurface);
                mMediaPlayer.prepareAsync();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
            if (mPlayerSurface != null) {
                mPlayerSurface.release();
            }
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {

        }
    };

    private void initVideoPlayer() {
        if (mMediaPlayer != null) {
            return;
        }
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setScreenOnWhilePlaying(true);

        mMediaPlayer.setOnPreparedListener(mOnPreparedListener);
        mMediaPlayer.setLooping(false);
        mMediaPlayer.setOnPreparedListener(mp -> {
            //为了解决部分手机锁屏会重置SurfaceTexture，在后台恢复播放的问题
            if (!isBackground) {
                mMediaPlayer.start();
            }
        });
        mMediaPlayer.setOnCompletionListener(mp -> {
            mMediaPlayer.reset();
            try {
                mMediaPlayer.setDataSource(mVideoPath);
                mMediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isBackground = false;
        if (mMediaPlayer != null) {
            mMediaPlayer.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isBackground = true;
        if (mMediaPlayer != null) {
            mMediaPlayer.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private final MediaPlayer.OnPreparedListener mOnPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
            int vw = mp.getVideoWidth();
            int vh = mp.getVideoHeight();

            if (mRatio == 0) {
                setTextureViewParams(((float) vw) / vh);
            }
        }
    };

    /**
     * 设置textureView导入的视频比例
     *
     * @param ratio x/y
     */
    private void setTextureViewParams(float ratio) {
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        mTextureView.getLayoutParams().width = screenWidth;
        mTextureView.getLayoutParams().height = (int) (screenWidth / ratio);
    }
}
